﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace ProjectJourney
{   
    public class Character : MonoBehaviour 
    {
        [SerializeField]public float speed;
        [SerializeField]private float _jumpForce;
        [SerializeField]private float _distance;
        [SerializeField]private GameObject _bottomCheck;
        [SerializeField]private LayerMask _groundMask;
        private Rigidbody2D _playerRb;
        private BoxCollider2D _playerColl; 
        [SerializeField]private Animator _anim;
        private bool _faceRight;
        private float _xVelocity;
        private bool isJump, isFall, isOnGround, jumpPressed;

        void Start(){
            _faceRight = true;
            _playerRb = GetComponent<Rigidbody2D>();
            _playerColl = GetComponent<BoxCollider2D>();
            _anim = GetComponent<Animator>();
        }

        void Update(){
            _xVelocity = Input.GetAxis("Horizontal") * speed;
            jumpPressed = Input.GetButtonDown("Jump");
        }

        private void FixedUpdate() {
            HandleMovement();
            UpdateAnim();
        }

        void HandleMovement(){
            
            _playerRb.velocity = new Vector2(_xVelocity, _playerRb.velocity.y);
            
            GroundCheck();
            
            if(jumpPressed && isOnGround){
                isJump = true;
                isFall = false;
                _playerRb.AddForce(new Vector2(0, _jumpForce), ForceMode2D.Impulse);
            }else if(isJump && _playerRb.velocity.y < 0){
                isJump = false;
                isFall = true;
            }else if(_playerColl.IsTouchingLayers(_groundMask)){
                isFall = false;
            }
            
            if(_playerRb.velocity.x < 0 && _faceRight){
                Flip();
            }else if(_playerRb.velocity.x > 0 && !_faceRight){
                Flip();
            }
        }

        void UpdateAnim(){
            _anim.SetBool("isJump", isJump);
            _anim.SetBool("isFall", isFall);
            _anim.SetBool("isRun", (_playerRb.velocity.x != 0));
            _anim.SetBool("isOnGround", isOnGround);
        }
        void GroundCheck(){
            Collider2D[] colliders = Physics2D.OverlapCircleAll(_bottomCheck.transform.position, _distance, _groundMask);
            for (int i = 0; i < colliders.Length; i++)
            {
                if (colliders[i].gameObject != gameObject)
                {
                    isOnGround = true;
                    return;
                }
            }
            isOnGround = false;
        }

        void Flip(){
            _faceRight = !_faceRight;

            Vector3 scale = transform.localScale;
            scale.x *= -1;
            transform.localScale = scale; 
        }
    }
}
